package org.example;/*
 * title:
 * author:
 * date:
 * description:
 * */

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/maxc")
public class MaxDateC {
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    /*private ThreadPoolTaskExecutor executor;

    @Autowired
    public void setThreadPoolTaskExecutor(ThreadPoolTaskExecutor executor) {
        this.executor = executor;
    }*/

    @GetMapping("/maxDateC")
    public String maxDateC() {

        long start = System.currentTimeMillis();

        List<LocalDate> latestDateC = new ArrayList<>();
        CompletableFuture<Void> productFuture = CompletableFuture.runAsync(() -> {
            String baseUrlParamsProduct = "aaa";
            LocalDate latestDateCProduct = maxDateCProduct(baseUrlParamsProduct);
            System.out.println("最晚的doc日期是：" + latestDateCProduct);
            latestDateC.add(latestDateCProduct);
        }, threadPoolTaskExecutor);

        CompletableFuture<Void> knowFuture = CompletableFuture.runAsync(() -> {
            String baseUrlParamsKnow = "bbb";
            LocalDate latestDateCKnow = maxDateCKnow(baseUrlParamsKnow);
            System.out.println("最晚的case日期是：" + latestDateCKnow);
            latestDateC.add(latestDateCKnow);
        }, threadPoolTaskExecutor);

        CompletableFuture<Void> softFuture = CompletableFuture.runAsync(() -> {
            String baseUrlParamsSoft = "ccc";
            LocalDate latestDateCSoft = maxDateCSoft(baseUrlParamsSoft);
            System.out.println("最晚的soft日期是：" + latestDateCSoft);
            latestDateC.add(latestDateCSoft);
        }, threadPoolTaskExecutor);

        CompletableFuture<Void> bullFuture = CompletableFuture.runAsync(() -> {
            String baseUrlParamsBull = "ddd";
            LocalDate latestDateCBull = maxDateCBull(baseUrlParamsBull);
            System.out.println("最晚的news日期是：" + latestDateCBull);
            latestDateC.add(latestDateCBull);
        }, threadPoolTaskExecutor);

        CompletableFuture.allOf(productFuture, knowFuture, softFuture, bullFuture).join();

        LocalDate maxPublishDateC = latestDateC.stream()
                .max(Comparator.naturalOrder())
                .orElseThrow(() -> new IllegalStateException("集合为空，无法找到最晚日期"));
        System.out.println("maxPublishDateC日期是：" + maxPublishDateC);
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - start));
        return maxPublishDateC.toString();
    }

    private LocalDate maxDateCSoft(String baseUrlParams) {
        try {
            URL url = new URL(baseUrlParams.toString());

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 设置可以输出
            connection.setFixedLengthStreamingMode(0);
            // 设置请求属性
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 写入POST请求的数据（这里假设参数已经在URL中，通常POST请求会在下面这行写入参数，但按需调整）
            //OutputStream os = connection.getOutputStream();
            //os.write(params.getBytes(StandardCharsets.UTF_8));
            //os.flush();
            //os.close();

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { // 200或201表示成功
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect(); // 关闭连接

                String jsonStr = content.toString(); // 这里放置整个JSON字符串


                String publishTime = extractPublishTimesCSoft(jsonStr);
                System.out.println(publishTime);

                // 定义日期格式器，仅用于日期部分
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                // 提取每个字符串的日期部分并转换为LocalDate对象
                LocalDate latestDate = LocalDate.parse(publishTime, dateFormatter);

                return latestDate;

            } else {
                System.out.println("HTTP POST 请求失败，响应码: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String extractPublishTimesCSoft(String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        String issueTime = null;
        try {
            // 读取JSON字符串为JsonNode
            JsonNode rootNode = mapper.readTree(jsonStr);

            // 导航至vrToVersion -> all -> 第一个元素 -> issueTime
            JsonNode firstElementInAll = rootNode.path("vrToVersion").path("all").get(0);
            issueTime = firstElementInAll.path("issueTime").asText();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return issueTime;
    }

    public LocalDate maxDateCProduct(String baseUrlParamsProduct) {
        try {
            URL url = new URL(baseUrlParamsProduct.toString());

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 设置可以输出
            connection.setFixedLengthStreamingMode(0);
            // 设置请求属性
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 写入POST请求的数据（这里假设参数已经在URL中，通常POST请求会在下面这行写入参数，但按需调整）
            //OutputStream os = connection.getOutputStream();
            //os.write(params.getBytes(StandardCharsets.UTF_8));
            //os.flush();
            //os.close();

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { // 200或201表示成功
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect(); // 关闭连接

                String jsonStr = content.toString(); // 这里放置整个JSON字符串

                List<String> publishTimes = extractPublishTimes(jsonStr);

                System.out.println(publishTimes);
                // 定义日期格式器，仅用于日期部分
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                // 提取每个字符串的日期部分并转换为LocalDate对象
                List<LocalDate> dates = new ArrayList<>();
                for (String dateTimeStr : publishTimes) {
                    LocalDate date = LocalDate.parse(dateTimeStr.split(" ")[0], dateFormatter);
                    dates.add(date);
                }

                // 使用流和Comparator找出最晚的日期
                LocalDate latestDate = dates.stream()
                        .max(Comparator.naturalOrder())
                        .orElseThrow(() -> new IllegalStateException("集合为空，无法找到最晚日期"));

                return latestDate;
            } else {
                System.out.println("HTTP POST 请求失败，响应码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<String> extractPublishTimes(String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        List<String> publishTimes = new ArrayList<>();
        try {
            JsonNode rootNode = mapper.readTree(jsonStr);

            if (rootNode.has("lstAggBean") && rootNode.get("lstAggBean").isArray()) {
                for (JsonNode aggBean : rootNode.get("lstAggBean")) {
                    if (aggBean.has("nodeList") && aggBean.get("nodeList").isArray()) {
                        JsonNode nodeList = aggBean.get("nodeList");
                        if (!nodeList.isEmpty()) {
                            publishTimes.add(nodeList.get(0).get("publishTime").asText());
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return publishTimes;
    }

    public LocalDate maxDateCKnow(String baseUrlParams) {
        try {
            URL url = new URL(baseUrlParams.toString());

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 设置可以输出
            connection.setFixedLengthStreamingMode(0);
            // 设置请求属性
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 写入POST请求的数据（这里假设参数已经在URL中，通常POST请求会在下面这行写入参数，但按需调整）
            //OutputStream os = connection.getOutputStream();
            //os.write(params.getBytes(StandardCharsets.UTF_8));
            //os.flush();
            //os.close();

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { // 200或201表示成功
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect(); // 关闭连接

                String jsonStr = content.toString(); // 这里放置整个JSON字符串


                String publishTime = extractPublishTimesCKnow(jsonStr);
                System.out.println(publishTime);

                // 定义日期格式器，仅用于日期部分
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                // 提取每个字符串的日期部分并转换为LocalDate对象
                LocalDate latestDate = LocalDate.parse(publishTime.split(" ")[0], dateFormatter);

                return latestDate;

            } else {
                System.out.println("HTTP POST 请求失败，响应码: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String extractPublishTimesCKnow(String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        String firstPublishTime=null;
        try {
            // 使用readTree方法直接读取JSON字符串为JsonNode
            JsonNode rootNode = mapper.readTree(jsonStr);

            // 获取nodeList节点
            JsonNode nodeListNode = rootNode.path("nodeList");

            // 检查nodeList是否非空且有元素
            if (nodeListNode.isArray() && nodeListNode.size() > 0) {
                // 获取第一个元素的publishTime属性
                firstPublishTime = nodeListNode.get(0).path("publishTime").asText();
                System.out.println(firstPublishTime); // 输出publishTime
            } else {
                System.out.println("nodeList is empty or not an array.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return firstPublishTime;
    }

    public LocalDate maxDateCBull(String baseUrlParams) {
        try {
            URL url = new URL(baseUrlParams.toString());

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 设置可以输出
            connection.setFixedLengthStreamingMode(0);
            // 设置请求属性
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 写入POST请求的数据（这里假设参数已经在URL中，通常POST请求会在下面这行写入参数，但按需调整）
            //OutputStream os = connection.getOutputStream();
            //os.write(params.getBytes(StandardCharsets.UTF_8));
            //os.flush();
            //os.close();

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { // 200或201表示成功
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect(); // 关闭连接

                String jsonStr = content.toString(); // 这里放置整个JSON字符串


                String publishTime = extractPublishTimesCBull(jsonStr);
                System.out.println(publishTime);

                // 定义日期格式器，仅用于日期部分
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                // 提取每个字符串的日期部分并转换为LocalDate对象
                LocalDate latestDate = LocalDate.parse(publishTime.split(" ")[0], dateFormatter);

                return latestDate;

            } else {
                System.out.println("HTTP POST 请求失败，响应码: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String extractPublishTimesCBull(String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        String publishTime = null;
        try {
            // 解析JSON字符串为JsonNode
            JsonNode rootNode = mapper.readTree(jsonStr);

            // 获取nodeList数组的第一个元素
            JsonNode firstNode = rootNode.path("nodeList").get(0);

            // 从第一个元素中提取publishTime属性
            publishTime = firstNode.path("publishTime").asText();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return publishTime;
    }
}

